var rescount = 0; // 附件个数
var idindex = 1;//file的id
var idprefix = 'uploadfile_1_';//上传附件展示元素的id前缀
var existcount;//修改时已经上传的附件数
var xhr = new XMLHttpRequest();
var data;//上传后返回的response信息
//返回 webapp 跟路径
function getWebRootPath() {
	var strFullPath = window.document.location.href;
	var strPath = window.document.location.pathname;
	var pos = strFullPath.indexOf(strPath);
	var prePath = strFullPath.substring(0,pos);
	var postPath = strPath.substring(0, strPath.substr(1).indexOf('/')+1);
	
	return(prePath+postPath);
}
function uploadImg(obj, jsessionid, articleid, uploadLimit, maxsize, filetype, filetypetip, excount) {
	var that = obj;
	var file = that.files[0];
	file.id = idprefix + idindex;
	existcount = excount;
	idindex++;
	data = '';
	fileSelected(file, uploadLimit, maxsize, filetype, filetypetip, jsessionid, articleid);
}
function fileSelected(file, uploadLimit, maxsize, filetype, filetypetip, jsessionid, articleid) {
	var total = rescount + existcount;
	//判断是否超过了上传数量的限制
	if (total > uploadLimit - 1){
		mui.toast( '上传文件数量超过了限制的' + uploadLimit + '个！' );
		//刷新input  
		var jqObj = $('#uploadfile');  
        jqObj.val("");
    	return;
	}
	//文件类型判断
	filetype = '\\' + filetype.replace( /\;/g, '$|\\' ).replace( /\*/g, '' ) + '$';
    var acceptreg = new RegExp( filetype, 'i' );
    if (  $.trim( acceptreg.exec( file.name ) ) == "" ) {
    	mui.toast( '文件 [' + file.name + '] 类型不正确！' );
    	return;
    }
    
    //判断文件大小
    maxsize = parseInt( maxsize, 10 );
    sourceSize = toFixed2(file.size / 1024/ 1024);
    if (sourceSize > (maxsize)) {
		mui.toast('文件超过了'+ maxsize +',请重新选择~');
		return;
	}
    var fileName = file.name;
    if ( fileName.length > 15) {
    	fileName = fileName.substr(0, 14) + '...';
    }
    
    filediv = document.createElement('div');
    filediv.className = 'mui-col-xs-10 mui-h5 mui-pull-left mui-ellipsis';
    filediv.innerHTML = fileName + '(' + formatSize( file ) + ')';
    
    deldiv = document.createElement('div');
    deldiv.className = 'mui-col-xs-2 mui-pull-right';
    a = document.createElement('a');
    a.href = 'javascript:uploadDelete("' + file.id + '")';
    span = document.createElement('span');
    span.className = 'mui-icon mui-icon-close mui-pull-right';
    a.appendChild(span);
    deldiv.appendChild(a);

    cleardiv = document.createElement('div');
    cleardiv.className = 'mui-clearfix';
    
    input = document.createElement('input');
    input.id = 'rid_' + file.id;
    input.type = 'hidden';
    
    div = document.createElement('div');
    div.id = file.id;
    div.className = 'row padding15 mui-ellipsis';
    div.appendChild(filediv);
    div.appendChild(deldiv);
    div.appendChild(input);
    div.appendChild(cleardiv);
    
    document.querySelector('#upload-container').appendChild(div);
    
    uploadFile(file, jsessionid, articleid);
}
function uploadFile(file, jsessionid, articleid) {
	var fd = new FormData();
    fd.append("up", file);
    //回调函数      
    xhr.onreadystatechange = function(){   
        if(xhr.readyState == 4 && xhr.status == 200){      
        	data = xhr.responseText;      
        	uploadComplete(file);
        }      
    }; 
    xhr.upload.addEventListener("progress", uploadProgress, false);
//    xhr.addEventListener("load", function () { uploadComplete(file) }, false);
    xhr.addEventListener("error", function () { uploadFailed(file) }, false);
    xhr.addEventListener("abort", uploadCanceled, false);
    xhr.open('POST', getWebRootPath()+ '/m/bbs/rtarticle/rt_att_add.do;jsessionid=' + jsessionid +'?rt_edit_id='+articleid, true);
    
    xhr.send(fd);
}
   
function uploadProgress(evt) {
    if (evt.lengthComputable) {
      var percentComplete = Math.round(evt.loaded * 100 / evt.total);
//      document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
    }
    else {
//      document.getElementById('progressNumber').innerHTML = 'unable to compute';
    }
}

function uploadComplete(file) {
    /* This event is raised when the server send back a response */
	if (data == "") {
		window.location.reload(); 
	}else{
		if(!isJSON(data)) {
			$("#"+file.id+" span.data").html(" - 上传失败");
			$("#"+file.id).addClass("uploadify-error");
			$("#"+file.id).find(".uploadify-progress-bar").remove();
			mui.toast("文件["+file.name+"]上传失败！");
			rescount--;
			return;
		};
		var obj = eval("("+data+")");
		if (obj.msg.toUpperCase() == "OK") {
			rescount++;
			$('#rid_'+file.id).val(obj.rt_res_id);
			//刷新input  
			var jqObj = $('#uploadfile');  
	        jqObj.val("");  
		} else {
			mui.toast("文件["+file.name+"]上传失败:"+obj.msg);
		}
	}
}

function uploadFailed(file) {
	mui.toast("文件["+file.name+"]上传失败:"+obj.msg);
}

function uploadCanceled(evt) {
	mui.toast("The upload has been canceled by the user or the browser dropped the connection.");
}
function uploadDelete(resid) {
	var v_resid = $('#rid_' + resid).val();
	if(v_resid == ""){
		$('#'+resid).delay(300).fadeOut(300, function() {$(this).remove();});// div直接消失
		rescount--;
		//刷新input  
		var jqObj = $('#uploadfile');  
        jqObj.val("");
		return;
	}
	
    var delxhr = new XMLHttpRequest();
    //2.设置回调函数      
    delxhr.onreadystatechange = function () {
    	if(delxhr.readyState == 4 && delxhr.status == 200){
    		$('#'+resid).delay(300).fadeOut(300, function() {$(this).remove();});
    		rescount--;
    		//刷新input  
			var jqObj = $('#uploadfile');  
	        jqObj.val("");
    	}
    }; 
    delxhr.open('POST', getWebRootPath()+"/m/bbs/rtarticle/rt_res_remove_" + v_resid + ".do");
    
    delxhr.send(null);
}

/*     
 * 相关附件列表，初始化
 * 参数如下：
 *   filedomID   - 对应 展示文件列表的 DOM ID
 *   fileJsonStr - 附件的数据 JSON 格式字符串
 */
function init_mobile_attachments(filedomID, fileJsonStr) {

	//if ($('#'+filedomID+'-queue').length<1) alert("not init over..."); // hzj debug
	//$('#'+filedomID+'-queue').html("正在初始化已存在的附件...");
	$.each(fileJsonStr, function(i, item) {
		var v_fileID = 'EXIST_'+item.rt_res_id;
		var fileName = item.rt_res_orig_name;
		if (fileName.length > 15) { //hzj change to 33
			fileName = fileName.substr(0,14) + '...';
		}
		var filediv = document.createElement('div');
	    filediv.className = 'mui-col-xs-10 mui-h5 mui-pull-left mui-ellipsis';
	    filediv.innerHTML = fileName + '(' + item.rt_res_size + ')';
	    
	    var deldiv = document.createElement('div');
	    deldiv.className = 'mui-col-xs-2 mui-pull-right';
	    var a = document.createElement('a');
	    a.href = 'javascript:uploadDelete("' + v_fileID + '")';
	    var span = document.createElement('span');
	    span.className = 'mui-icon mui-icon-close mui-pull-right';
	    a.appendChild(span);
	    deldiv.appendChild(a);

	    var cleardiv = document.createElement('div');
	    cleardiv.className = 'mui-clearfix';
	    
	    var input = document.createElement('input');
	    input.id = 'rid_' + v_fileID;
	    input.type = 'hidden';
	    input.value = item.rt_res_id;
	    
	    var div = document.createElement('div');
	    div.id = v_fileID;
	    div.className = 'row padding15 mui-ellipsis';
	    div.appendChild(filediv);
	    div.appendChild(deldiv);
	    div.appendChild(input);
	    div.appendChild(cleardiv);
	    
	    document.querySelector('#'+filedomID).appendChild(div);
	});
}

function toFixed2 (num) {
    return parseFloat(+num.toFixed(2));
}
function formatSize(file){
	var fileSize = (file.size / 1024); //
    var suffix = ' KB';
    if (fileSize > 1024) {
        fileSize = (fileSize / 1024); // 
        suffix = ' MB';
    }
    var fileSizeParts = fileSize.toString().split('.');
    fileSize = fileSizeParts[0];
    if (fileSizeParts.length > 1) {
        fileSize += '.' + fileSizeParts[1].substr(0, 2);
    }
    return fileSize += suffix;
}
/**
 * 替换字符串 !{}
 * @param obj
 * @returns {String}
 * @example
 * '我是!{str}'.render({str: '测试'});
 */
String.prototype.render = function (obj) {
    var str = this, reg;

    Object.keys(obj).forEach(function (v) {
        reg = new RegExp('\\!\\{' + v + '\\}', 'g');
        str = str.replace(reg, obj[v]);
    });

    return str;
};

/**
 * 触发事件 - 只是为了兼容演示demo而已
 * @param element
 * @param event
 * @returns {boolean}
 */
function fireEvent (element, event) {
    var evt;

    if (document.createEventObject) {
        // IE浏览器支持fireEvent方法
        evt = document.createEventObject();
        return element.fireEvent('on' + event, evt)
    }
    else {
        // 其他标准浏览器使用dispatchEvent方法
        evt = document.createEvent('HTMLEvents');
        // initEvent接受3个参数：
        // 事件类型，是否冒泡，是否阻止浏览器的默认行为
        evt.initEvent(event, true, true);
        return !element.dispatchEvent(evt);
    }
}

//判断是不是json格式的字符串
function isJSON(obj) {
	if(!obj.match("^\{(.+:.+,*){1,}\}$")) {
		return false;
	}    
	return true;
}